import { useEffect, useState, useRef } from 'react'
import { Link } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import {
  Package,
  Zap,
  Activity,
  TrendingUp,
  Plus,
  ArrowRight,
  RefreshCw
} from 'lucide-react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../components/ui/Card'
import { Button } from '../components/ui/Button'
import { Badge } from '../components/ui/Badge'
import { PluginCard } from '../components/PluginCard'
import { PluginErrorBoundary } from '../components/PluginErrorBoundary'
import { createPortal } from 'react-dom'

interface MarketItem {
  name: string
  manifest: string
  enabled: boolean
}

interface PluginManifest {
  name: string
  version: string
  description?: string
  author?: string
  icon?: string
}

interface DashboardProps {
  market: MarketItem[]
  pluginUIs: Record<string, () => JSX.Element>
  onTogglePlugin: (plugin: MarketItem) => void
  onConfigurePlugin: (plugin: MarketItem) => void
  onRescanPlugins: () => void
  rescanLoading: boolean
  theme: 'light' | 'dark'
}

function ShadowRootHost(props: { children: React.ReactNode; style?: React.CSSProperties; className?: string }) {
  const hostRef = useRef<HTMLDivElement | null>(null)
  const [shadow, setShadow] = useState<ShadowRoot | null>(null)
  
  useEffect(() => {
    const el = hostRef.current
    if (!el) return
    let root = el.shadowRoot as ShadowRoot | null
    if (!root) {
      root = el.attachShadow({ mode: 'open' })
      const style = document.createElement('style')
      style.textContent = `:host{display:block} *{box-sizing:border-box}`
      root.appendChild(style)
    }
    setShadow(root)
  }, [])
  
  return (
    <div ref={hostRef} style={props.style} className={props.className}>
      {shadow ? createPortal(props.children, shadow as any) : null}
    </div>
  )
}

export function Dashboard({
  market,
  pluginUIs,
  onTogglePlugin,
  onConfigurePlugin,
  onRescanPlugins,
  rescanLoading,
  theme
}: DashboardProps) {
  const { t } = useTranslation()
  const [manifests, setManifests] = useState<Record<string, PluginManifest>>({})

  const enabledPlugins = market.filter(p => p.enabled)
  const totalPlugins = market.length
  const activePlugins = Object.keys(pluginUIs).length

  // Load plugin manifests
  useEffect(() => {
    const loadManifests = async () => {
      const manifestPromises = market.map(async (plugin) => {
        try {
          const res = await fetch(plugin.manifest)
          const manifest = await res.json()
          return { id: plugin.name, manifest }
        } catch (error) {
          console.warn(`Failed to load manifest for ${plugin.name}:`, error)
          return { id: plugin.name, manifest: null }
        }
      })
      
      const results = await Promise.all(manifestPromises)
      const manifestMap: Record<string, PluginManifest> = {}
      results.forEach(({ id, manifest }) => {
        if (manifest) manifestMap[id] = manifest
      })
      setManifests(manifestMap)
    }

    if (market.length > 0) {
      loadManifests()
    }
  }, [market])

  return (
    <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-8">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">{t('dashboard.title')}</h1>
          <p className="text-muted-foreground mt-1">
            {t('dashboard.subtitle')}
          </p>
        </div>

        <div className="flex items-center space-x-3">
          <Button
            variant="outline"
            onClick={onRescanPlugins}
            disabled={rescanLoading}
            loading={rescanLoading}
            className="flex items-center space-x-2"
          >
            <RefreshCw className="h-4 w-4" />
            <span>{t('dashboard.rescan')}</span>
          </Button>

          <Link to="/plugins">
            <Button className="flex items-center space-x-2">
              <Plus className="h-4 w-4" />
              <span>{t('dashboard.managePlugins')}</span>
            </Button>
          </Link>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">{t('dashboard.stats.totalPlugins')}</CardTitle>
            <Package className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalPlugins}</div>
            <p className="text-xs text-muted-foreground">
              {t('dashboard.stats.availableInSystem')}
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">{t('dashboard.stats.enabledPlugins')}</CardTitle>
            <Zap className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{enabledPlugins.length}</div>
            <p className="text-xs text-muted-foreground">
              {t('dashboard.stats.currentlyEnabled')}
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">{t('dashboard.stats.activePlugins')}</CardTitle>
            <Activity className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{activePlugins}</div>
            <p className="text-xs text-muted-foreground">
              {t('dashboard.stats.runningWithUI')}
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Active Plugins Section */}
      {enabledPlugins.length > 0 ? (
        <div className="space-y-6">
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-2xl font-semibold">{t('dashboard.activePlugins.title')}</h2>
              <p className="text-muted-foreground">
                {t('dashboard.activePlugins.subtitle')}
              </p>
            </div>
            <Link to="/plugins">
              <Button variant="ghost" className="flex items-center space-x-1">
                <span>{t('dashboard.activePlugins.viewAll')}</span>
                <ArrowRight className="h-4 w-4" />
              </Button>
            </Link>
          </div>

          {/* Plugin Cards */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {enabledPlugins.slice(0, 4).map((plugin) => (
              <PluginCard
                key={plugin.name}
                plugin={plugin}
                manifest={manifests[plugin.name]}
                onToggle={() => onTogglePlugin(plugin)}
                onConfigure={() => onConfigurePlugin(plugin)}
                compact
              />
            ))}
          </div>

          {enabledPlugins.length > 4 && (
            <div className="text-center">
              <Link to="/plugins">
                <Button variant="outline">
                  {t('dashboard.activePlugins.viewMore', { count: enabledPlugins.length - 4 })}
                </Button>
              </Link>
            </div>
          )}
        </div>
      ) : (
        <Card>
          <CardHeader>
            <CardTitle>{t('dashboard.noActivePlugins.title')}</CardTitle>
            <CardDescription>
              {t('dashboard.noActivePlugins.subtitle')}
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Link to="/plugins">
              <Button className="flex items-center space-x-2">
                <Package className="h-4 w-4" />
                <span>{t('dashboard.noActivePlugins.browsePlugins')}</span>
              </Button>
            </Link>
          </CardContent>
        </Card>
      )}

      {/* Plugin UI Rendering */}
      {Object.entries(pluginUIs).length > 0 && (
        <div className="space-y-6">
          <div>
            <h2 className="text-2xl font-semibold">{t('dashboard.pluginInterfaces.title')}</h2>
            <p className="text-muted-foreground">
              {t('dashboard.pluginInterfaces.subtitle')}
            </p>
          </div>

          <div className="grid grid-cols-1 gap-6">
            {Object.entries(pluginUIs).map(([name, Comp]) => (
              <Card key={name}>
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-3">
                      <div className="w-2 h-2 bg-green-500 rounded-full" />
                      <CardTitle className="text-lg">{manifests[name]?.name || name}</CardTitle>
                    </div>
                    <Badge variant="outline">{t('dashboard.pluginInterfaces.live')}</Badge>
                  </div>
                </CardHeader>
                <CardContent>
                  <PluginErrorBoundary
                    pluginName={manifests[name]?.name || name}
                    onReload={() => window.location.reload()}
                  >
                    <ShadowRootHost
                      className="min-h-[200px] rounded-lg border bg-muted/20 p-4"
                      style={{
                        ['--plugin-bg' as any]: theme === 'dark' ? 'hsl(var(--card))' : 'hsl(var(--card))',
                        ['--plugin-fg' as any]: theme === 'dark' ? 'hsl(var(--card-foreground))' : 'hsl(var(--card-foreground))',
                      }}
                    >
                      <Comp />
                    </ShadowRootHost>
                  </PluginErrorBoundary>
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}
